#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <signal.h>
#include <unistd.h>

#define COMMAND_VALUESIZE       100

char result[COMMAND_VALUESIZE] = "测试失败";

int sdcard_auto_test()
{
    int ret = 0;
    int status = 0;
    status = system("/userfs/sdcard_test.sh");
    if (status == -1) {
        printf("执行系统命令错误...\n");
        ret = -1;
    } else {
        printf("退出状态值 = [0x%x]\n", status);
        if (WIFEXITED(status)) {
            if (0 == WEXITSTATUS(status)) {
                printf("成功运行脚本。\n");
                ret = 0;
            } else {
                if (1 == WEXITSTATUS(status)) {
                    printf("运行脚本失败，脚本退出码: %d\n", WEXITSTATUS(status));
                    ret = 1;
                } else if (2 == WEXITSTATUS(status)) {
                    printf("运行脚本失败，脚本退出码: %d\n", WEXITSTATUS(status));
                    ret = 2;
                }
            }
        } else {
            printf("退出状态 = [%d]\n", WEXITSTATUS(status));
            ret = -1;
        }
    }

    if (ret != 0)
        printf("sata硬盘测试失败。ret = %d\n", ret);

    return ret;
}

int main(int argc, char *argv[])
{
    int test_flag = 0, err_code = 0;
    char buf[COMMAND_VALUESIZE] = "sdcard_test";

    printf("sata硬盘测试进程开始...\n");

    test_flag = sdcard_auto_test();
    if (test_flag == 0) {
        strcpy(result, "sata硬盘测试成功");
        err_code = 0;
        printf("sata硬盘测试通过\n");
        system("echo \"$(date)：sata硬盘测试成功\" >> /userfs/all.txt");
    } else if (test_flag == 1) {
        strcpy(result, "sata硬盘测试失败");
        err_code = 1;
        printf("sata硬盘测试挂载错误...\n");
        system("echo \"$(date)：sata硬盘挂载错误\" >> /userfs/all.txt");
    } else if (test_flag == 2) {
        strcpy(result, "sata硬盘测试失败");
        err_code = 2;
        printf("sata硬盘测试超时...\n");
        system("echo \"$(date)：sata硬盘测试超时\" >> /userfs/all.txt");
    }


    if (test_flag == 0) {
        int fd = -1;
        double cap;
        char sdcard_size[32] = { 0 };
        fd = open("/run/sd_capacity", O_RDONLY);
        memset(sdcard_size, 0, sizeof(sdcard_size));
        int r_len = read(fd, sdcard_size, sizeof(sdcard_size));
        if (r_len <= 0) {
            printf("读取 %s 失败, 错误码 = %d\n", "/run/sd_capacity", errno);
        }
        cap = strtod(sdcard_size, NULL);
        snprintf(sdcard_size, sizeof(sdcard_size), "容量：%.4fG ", cap * 1.0 / 1024 / 1024);
        strcat(buf, ": ");
        strcat(buf, sdcard_size);
    }
    
    printf("%s\n", result);
    return 0;
}
